/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * frmDatDichVu.java
 *
 * Created on Dec 8, 2011, 3:18:30 PM
 */
package uit.qlks.from;

import java.util.ArrayList;
import java.util.List;
import java.rmi.Naming;
import java.util.Hashtable;
import javax.sql.rowset.WebRowSet;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import uit.qlks.controller.loaidichvu.LoaiDichVuController;


public class frmDatDichVu extends javax.swing.JFrame {
    private List MaDV = new ArrayList();
    List MaDVDat = new ArrayList();
    List SoLuongDat = new ArrayList();
    private Hashtable<String , String> Gia = new Hashtable<String, String>();
    private boolean active;

    /** Creates new form frmDatDichVu */
    public frmDatDichVu() {
        initComponents();
        active = false;
        try{
            WebRowSet wrs = LoaiDichVuController.loaiDichVu_GetByAll();
            if(wrs != null)
            {
                while(wrs.next())
                {
                    cbDichVu.addItem(wrs.getString("TenDV"));
                    MaDV.add(wrs.getString("MaDV"));
                    Gia.put(wrs.getString("MaDV"),Format_Price(wrs.getString("Gia")));
                }
            }
            active = true;
            cbDichVu.setSelectedIndex(0);
            lbgia.setText(Gia.get(MaDV.get(0)));
        }
        catch(Exception e)
        {
            JOptionPane.showMessageDialog(new JFrame(), "Đường truyền bị gián đoạn ! Xin vui lòng kiểm tra lại", "Test Connect", JOptionPane.INFORMATION_MESSAGE);
        }
    }
    
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        btnDat = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tbPhieuThueDV = new javax.swing.JTable();
        btnXoa = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        cbDichVu = new javax.swing.JComboBox();
        jLabel3 = new javax.swing.JLabel();
        lbgia = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        txtSoLuong = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Đặt Dịch Vụ");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Times New Roman", 1, 18));
        jLabel1.setText("ĐẶT DỊCH VỤ");

        btnDat.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Image/Add.png"))); // NOI18N
        btnDat.setText("Đặt");
        btnDat.setBorder(null);
        btnDat.setContentAreaFilled(false);
        btnDat.setRolloverIcon(new javax.swing.ImageIcon(getClass().getResource("/Image/Add2.png"))); // NOI18N
        btnDat.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDatActionPerformed(evt);
            }
        });

        tbPhieuThueDV.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Dịch Vụ", "Số Lượng"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tbPhieuThueDV.getTableHeader().setReorderingAllowed(false);
        tbPhieuThueDV.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                tbPhieuThueDVMousePressed(evt);
            }
        });
        jScrollPane1.setViewportView(tbPhieuThueDV);

        btnXoa.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Image/Delete.png"))); // NOI18N
        btnXoa.setText("Xóa");
        btnXoa.setBorder(null);
        btnXoa.setContentAreaFilled(false);
        btnXoa.setRolloverIcon(new javax.swing.ImageIcon(getClass().getResource("/Image/Delete2.png"))); // NOI18N
        btnXoa.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnXoaActionPerformed(evt);
            }
        });

        jLabel2.setText("Loại Dịch Vụ:");

        cbDichVu.setMaximumSize(new java.awt.Dimension(20, 20));
        cbDichVu.setPreferredSize(new java.awt.Dimension(6, 20));
        cbDichVu.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                cbDichVuItemStateChanged(evt);
            }
        });

        jLabel3.setText("Giá:");

        lbgia.setText("0 VNĐ");

        jLabel4.setText("Số Lượng:");

        txtSoLuong.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtSoLuongKeyTyped(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addComponent(jLabel4)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lbgia)
                    .addComponent(txtSoLuong, javax.swing.GroupLayout.PREFERRED_SIZE, 147, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cbDichVu, javax.swing.GroupLayout.PREFERRED_SIZE, 148, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(cbDichVu, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(lbgia))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 13, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(txtSoLuong, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(19, 19, 19))
        );

        jLabel5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Image/services-icon.png"))); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(64, 64, 64)
                        .addComponent(jLabel5))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(43, 43, 43)
                        .addComponent(btnDat, javax.swing.GroupLayout.PREFERRED_SIZE, 62, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(37, 37, 37)
                        .addComponent(btnXoa, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 375, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 128, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel1)
                        .addGap(127, 127, 127)))
                .addContainerGap(20, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(28, 28, 28)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(18, 18, 18)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 239, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel5, 0, 0, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(btnDat)
                            .addComponent(btnXoa))))
                .addContainerGap(20, Short.MAX_VALUE))
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-670)/2, (screenSize.height-365)/2, 670, 365);
    }// </editor-fold>//GEN-END:initComponents
// Hàm xử lý chỉ cho nhập số vào text field
private void txtSoLuongKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtSoLuongKeyTyped
    char c = evt.getKeyChar();
    if(!Character.isDigit(c) )
    {
        evt.consume();
    }
}//GEN-LAST:event_txtSoLuongKeyTyped

private void btnDatActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDatActionPerformed
    if(cbDichVu.getSelectedIndex() == -1)
    {
        JOptionPane.showMessageDialog(this, "Không còn dịch vụ để đặt.","Warning", JOptionPane.WARNING_MESSAGE);
        return;
    }
    if("".equals(txtSoLuong.getText()))
    {
        JOptionPane.showMessageDialog(this, "Bạn vui lòng nhập số lượng!","Warning", JOptionPane.WARNING_MESSAGE);
        txtSoLuong.requestFocusInWindow();
        return;
    }

    String dv = this.cbDichVu.getSelectedItem().toString();
    String sl = this.txtSoLuong.getText().toString();
    int index = cbDichVu.getSelectedIndex();
    MaDVDat.add(MaDV.get(index));
    //SoLuongDat.add(sl);
    this.UpdateTable(tbPhieuThueDV, tableColumnsName, dv, sl);

    this.cbDichVu.removeItemAt(index);  
    this.MaDV.remove(index);
    txtSoLuong.requestFocusInWindow();
    //this.btnDat.setEnabled(false);
}//GEN-LAST:event_btnDatActionPerformed

private void btnXoaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnXoaActionPerformed
    int i = this.tbPhieuThueDV.getSelectedRow();
        if(i==-1)
        {
            JOptionPane.showMessageDialog(rootPane, "Bạn vui lòng chọn Dịch Vụ để thao tác","Warning", JOptionPane.WARNING_MESSAGE);
            return;
        }
        try{
            if(JOptionPane.showConfirmDialog(this, "Bạn có chắc chắn  muốn xóa không ?", "Question",JOptionPane.YES_NO_OPTION)!=1)
            {
                DefaultTableModel model = new DefaultTableModel(); 
                model = (DefaultTableModel) tbPhieuThueDV.getModel();    
                int array[] = tbPhieuThueDV.getSelectedRows(); 
                for (int j = 0; j < array.length; j++)
                { 
                    MaDV.add(MaDVDat.get(array[j] - j));
                    MaDVDat.remove(array[j] - j);
                    cbDichVu.addItem(tbPhieuThueDV.getValueAt(array[j] - j, 0));
                    model.removeRow(array[j] - j); 
                } 
                lbgia.setText(Gia.get(MaDV.get(cbDichVu.getSelectedIndex())).toString());
            }
            else
            {
                return;
            }
        }
        catch(Exception e)
        {
            System.out.println(e);
        }
}//GEN-LAST:event_btnXoaActionPerformed

private void tbPhieuThueDVMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbPhieuThueDVMousePressed
    try{
//        this.cbDichVu.setSelectedItem(tbPhieuThueDV.getValueAt(this.tbPhieuThueDV.getSelectedRow(), 0).toString());
        this.txtSoLuong.setText(tbPhieuThueDV.getValueAt(this.tbPhieuThueDV.getSelectedRow(), 1).toString());
        lbgia.setText(Gia.get(MaDVDat.get(tbPhieuThueDV.getSelectedRow())));
//        this.btnXoa.setEnabled(true);
//        this.btnDat.setEnabled(false);
//        this.cbDichVu.setEnabled(false);
    }
    catch(Exception e)
    {
        
    }
}//GEN-LAST:event_tbPhieuThueDVMousePressed

private void cbDichVuItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cbDichVuItemStateChanged

    try
    {
    if(active)
    {
        lbgia.setText(Gia.get(MaDV.get(cbDichVu.getSelectedIndex())));
    }
    }catch(Exception e)
    {
        lbgia.setText("0 VNĐ");
    }
    // TODO add your handling code here:
}//GEN-LAST:event_cbDichVuItemStateChanged

private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
    frmDatPhong._frm.setVisible(true);
    frmDatPhong._frm.setFocusable(true);
    // TODO add your handling code here:
}//GEN-LAST:event_formWindowClosed

private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
    frmDatPhong._frm.GiaDV = Gia;
    frmDatPhong._frm.MaDV = MaDVDat;
    frmDatPhong._frm.BangDV = this.tbPhieuThueDV;
    frmDatPhong._frm.setdichvu();
    // TODO add your handling code here:
}//GEN-LAST:event_formWindowClosing
public void setopen()
{
    int index;
    for(int i=0;i< MaDVDat.size();i++)
    {
        index = MaDV.indexOf(MaDVDat.get(i));
        this.UpdateTable(tbPhieuThueDV,tableColumnsName, cbDichVu.getItemAt(index).toString(), SoLuongDat.get(i).toString());
        
        this.cbDichVu.removeItemAt(index);  
        this.MaDV.remove(index);
    }
    
    //MaDVDat.indexOf(Gia);
}
private String[] tableColumnsName = {"Dịch Vụ","Số Lượng "};
private void UpdateTable(JTable jt, String[] tableColumnsName, String dv, String sl){
        try{
            DefaultTableModel dfTable = (DefaultTableModel) jt.getModel();
            dfTable.setColumnIdentifiers(tableColumnsName);
            Vector rowData;
            rowData = new Vector() ;
            rowData.add(dv);
            rowData.add(sl);
            dfTable.addRow(rowData);
            jt.setModel(dfTable);
        }
        catch(Exception e)
        {
            System.out.println(e);
        }
    }

///<editor-fold defaultstate="collapsed" desc=" Format_Price ">
    private String Format_Price(String Price)
        {
            if ("0".equals(Price))
            {
                return "";
            }
            else
                Price = Price.replace(".0000", "");
            Price = Price.replace(",", "");
            String tmp = "";
            while (Price.length() > 3)
            {
                tmp = "." + Price.substring(Price.length() - 3) + tmp;
                Price = Price.substring(0, Price.length() - 3);
            }
            tmp = Price + tmp + " VNĐ";
            return tmp;
        }
    //</editor-fold>
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(frmDatDichVu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(frmDatDichVu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(frmDatDichVu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(frmDatDichVu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new frmDatDichVu().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnDat;
    private javax.swing.JButton btnXoa;
    private javax.swing.JComboBox cbDichVu;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lbgia;
    private javax.swing.JTable tbPhieuThueDV;
    private javax.swing.JTextField txtSoLuong;
    // End of variables declaration//GEN-END:variables
}
